package com.jsz.peini.server.thread;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.jsz.peini.bean.order.OrderException;
import com.jsz.peini.bean.order.OrderExceptionExample;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.order.OrderExceptionMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;


public class OrderExceptionThread extends Thread{
	
	Logger logger = Logger.getLogger(OrderExceptionThread.class);
	
	public void init(){
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		OrderExceptionMapper orderExceptionMapper = (OrderExceptionMapper)SpringContextUtil.getBean(OrderExceptionMapper.class);
		
		while(true)
		{
			try {
				List<byte[]> list = RedisUtil.brpop(RedisConstants.ORDER_EXCEPTION.getBytes());
				if(list.size() > 1){
					byte [] order = list.get(1);
					OrderInfo title = (OrderInfo)SerializeUtil.unserialize(order);
					
					OrderException orException = new OrderException();
					
					OrderExceptionExample example = new OrderExceptionExample();
					example.createCriteria().andOrderIdEqualTo(title.getId().toString());
					List<OrderException> exList = orderExceptionMapper.selectByExampleWithBLOBs(example);
					if(exList.size() > 0){
						orException = exList.get(0);
						orException.setDealTime(new Date());
						orderExceptionMapper.updateByPrimaryKeySelective(orException);
					}else{
						orException.setCreateTime(new Date());
						orException.setExId(UUID.randomUUID().toString().replace("-", ""));
						orException.setExStatus(0);
						orException.setOrderId(title.getId().toString());
						orderExceptionMapper.insertSelective(orException);
					}
				}
				
				Thread.sleep(1);
			} catch (Exception e1) {
				e1.printStackTrace();
				logger.info("fail", e1);
			}
		}
		
	}
	
}